﻿using System;
using System.Reflection;
using UnityEngine;
using Framework.Util;

namespace Framework.Singleton
{
    public class SingletonMonoBehaviour<T> : MonoBehaviour
        where T : SingletonMonoBehaviour<T>
    {
        protected SingletonMonoBehaviour()
        {
            Type type = typeof(T);
            ConstructorInfo[] constructors = type.GetConstructors();
            if (constructors.Length > 0)
            {
                string errorMessage = string.Format("{0} has at least one accesible constructor.", type.Name);
#if UNITY_EDITOR
                throw new Exception(errorMessage);
#else
                Debug.LogError(errorMessage);
#endif
            }
        }

        private static T instance;
        /// <summary>获取实例</summary>
        public static T Instance
        {
            get
            {
                string path = SingletonPath;
                GameObject aimGameObject = UtilCollection.GameObjectUtil.FindOrCreateGameObject(path);
                instance = aimGameObject.GetComponent<T>();

                if (instance == null)
                    instance = aimGameObject.AddComponent<T>();

                return instance;
            }
        }

        /// <summary>单例路径</summary>
        private static string SingletonPath
        {
            get
            {
                string path = string.Empty;

                Type derivedType = typeof(T);
                PropertyInfo propertyInfo = derivedType.GetProperty("SingletonPath");
                if (propertyInfo != null)
                    path = propertyInfo.GetValue(null) as string;

                if (string.IsNullOrEmpty(path))
                {
                    Type baseType = derivedType.BaseType;
                    while (baseType != null)
                    {
                        if (baseType.Name == "SingletonMonoBehaviour`1")
                        {
                            path = "SingletonMonoBehaviour";
                            break;
                        }
                        else
                        {
                            PropertyInfo basePropertyInfo = baseType.GetProperty("SingletonPath");
                            if (basePropertyInfo != null)
                            {
                                path = basePropertyInfo.GetValue(null) as string;
                                break;
                            }
                        }

                        baseType = baseType.BaseType;
                    }
                }
                return path;
            }
        }

        /// <summary>防止重复动态创建</summary>
        private void Awake()
        {
            GameObject aimGameObject = GameObject.Find(SingletonPath);
            if (gameObject != aimGameObject)
            {
                GameObject.DestroyImmediate(this, true);
            }
            else if (aimGameObject != null && gameObject == aimGameObject)
            {
                T[] t = aimGameObject.GetComponents<T>();
                if (t.Length > 1)
                    GameObject.DestroyImmediate(this, true);
                else
                    instance = t[0];
            }
        }

        /// <summary>防止重复挂接脚本</summary>
        private void Reset()
        {
            GameObject aimGameObject = GameObject.Find(SingletonPath);
            if (gameObject != aimGameObject)
            {
                GameObject.DestroyImmediate(this, true);
            }
            else if (aimGameObject != null && gameObject == aimGameObject)
            {
                T[] t = aimGameObject.GetComponents<T>();
                if (t.Length > 1)
                    GameObject.DestroyImmediate(this, true);
            }
        }
    }
}